package com.cyt.work.antiepidemic.service.impl;

import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.collection.CollUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.DictCode;
import com.cyt.base.util.ErrorCode;
import com.cyt.base.util.StringUtils;
import com.cyt.sys.model.po.SysDictContent;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.sys.util.EasyPoiUtil;
import com.cyt.work.antiepidemic.dao.AntiepidemicBuildingDao;
import com.cyt.work.antiepidemic.model.po.AntiepidemicBuilding;
import com.cyt.work.antiepidemic.model.vo.AntiepidemicBuildingVo;
import com.cyt.work.antiepidemic.model.vo.AntiepidemicCommunityImportVo;
import com.cyt.work.antiepidemic.model.vo.AntiepidemicCommunityVerifyImportVo;
import com.cyt.work.antiepidemic.model.vo.AntiepidemicSelectVo;
import com.cyt.work.antiepidemic.service.AntiepidemicBuildingService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

/**
 * e门通-社区建筑信息Service层实现类
 *
 * @author rong yuan
 * @date 2020-2-12 1:38:40
 */
@Service("antiepidemicBuildingService")
public class AntiepidemicBuildingServiceImpl extends BaseServiceImpl<AntiepidemicBuilding> implements AntiepidemicBuildingService {

    @Resource
    private AntiepidemicBuildingDao antiepidemicBuildingDao;

    @Autowired
    public void setBaseDao(AntiepidemicBuildingDao antiepidemicBuildingDao) {
        this.baseDao = antiepidemicBuildingDao;
    }

    /**
     * 分页查询
     *
     * @param antiepidemicBuildingVo 接受参数对象
     * @param pageNum                分页数
     * @param pageSize               每页显示条数
     * @return ReturnResult
     * @author rong yuan
     * @date 2020-2-12 1:38:40
     */
    @Override
    public ReturnResult page(AntiepidemicBuildingVo antiepidemicBuildingVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" order_num asc, create_time desc");
        List<AntiepidemicBuildingVo> list = antiepidemicBuildingDao.selectByCondition(antiepidemicBuildingVo);
        PageInfo<AntiepidemicBuildingVo> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param antiepidemicBuildingVo 参数接受对象
     * @param sysUser                当前用户
     * @return ReturnResult
     * @author rong yuan
     * @date 2020-2-12 1:38:40
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(AntiepidemicBuildingVo antiepidemicBuildingVo, SysUser sysUser) {
        if (StringUtils.isBlank(antiepidemicBuildingVo.getId())) {
            AntiepidemicBuilding antiepidemicBuilding = new AntiepidemicBuilding(sysUser);
            antiepidemicBuilding.setApplyId(antiepidemicBuildingVo.getApplyId());
            antiepidemicBuilding.setCommunityId(antiepidemicBuildingVo.getCommunityId());
            antiepidemicBuilding.setBuildingInfo(antiepidemicBuildingVo.getBuildingInfo());
            antiepidemicBuilding.setOrderNum(antiepidemicBuildingVo.getOrderNum());
            antiepidemicBuildingDao.insert(antiepidemicBuilding);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            AntiepidemicBuilding antiepidemicBuilding = antiepidemicBuildingDao.selectByPrimaryKey(antiepidemicBuildingVo.getId());
            antiepidemicBuilding.setApplyId(antiepidemicBuildingVo.getApplyId());
            antiepidemicBuilding.setCommunityId(antiepidemicBuildingVo.getCommunityId());
            antiepidemicBuilding.setBuildingInfo(antiepidemicBuildingVo.getBuildingInfo());
            antiepidemicBuilding.setOrderNum(antiepidemicBuildingVo.getOrderNum());
            antiepidemicBuilding.setUpdateTime(new Date());
            antiepidemicBuilding.setUpdateUser(sysUser.getId());
            antiepidemicBuildingDao.updateByPrimaryKey(antiepidemicBuilding);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }

    /**
     * 根据条件逻辑删除
     *
     * @param antiepidemicBuildingVo 参数接受对象
     * @param sysUser                当前用户
     * @return ReturnResult
     * @author rong yuan
     * @date 2020-2-12 1:38:40
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(AntiepidemicBuildingVo antiepidemicBuildingVo, SysUser sysUser) {
        //要修改的字段
        AntiepidemicBuilding antiepidemicBuilding = new AntiepidemicBuilding();
        antiepidemicBuilding.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        antiepidemicBuilding.setUpdateUser(sysUser.getId());
        antiepidemicBuilding.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(AntiepidemicBuilding.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(antiepidemicBuildingVo.getId())) {
            criteria.andIn("id", Arrays.asList(antiepidemicBuildingVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        antiepidemicBuildingDao.updateByExampleSelective(antiepidemicBuilding, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param antiepidemicBuildingVo 参数接受对象
     * @param sysUser                当前用户
     * @return ReturnResult
     * @author rong yuan
     * @date 2020-2-12 1:38:40
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(AntiepidemicBuildingVo antiepidemicBuildingVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(AntiepidemicBuilding.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(antiepidemicBuildingVo.getId())) {
            criteria.andIn("id", Arrays.asList(antiepidemicBuildingVo.getId().split(",")));
        }
        antiepidemicBuildingDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    @Override
    public ReturnResult acceptSelect(String code, String communityId) {
        AntiepidemicBuildingVo antiepidemicBuildingVo = new AntiepidemicBuildingVo();
        antiepidemicBuildingVo.setCommunityId(communityId);
        List<AntiepidemicBuildingVo> list = antiepidemicBuildingDao.selectByCondition(antiepidemicBuildingVo);
        List<SysDictContent> sysDictContentList = new ArrayList<>();
        for (AntiepidemicBuildingVo entity : list) {
            SysDictContent sysDictContent = new SysDictContent();
            sysDictContent.setId(entity.getId());
            sysDictContent.setName(entity.getBuildingInfo());
            sysDictContent.setDictType(code);
            sysDictContent.setValue(entity.getId());
            sysDictContentList.add(sysDictContent);
        }
        return new ReturnResult(sysDictContentList);
    }

    @Override
    public List<AntiepidemicSelectVo> selectAntiepidemicSelectVoList(AntiepidemicBuilding antiepidemicBuildingSearch) {
        return antiepidemicBuildingDao.selectAntiepidemicSelectVoList(antiepidemicBuildingSearch);
    }

    @Override
    public ReturnResult importExcel(MultipartFile file, String applyId, String communityId, SysUser sysUser) {
        // 用户表中是否存在数据
        ExcelImportResult<AntiepidemicCommunityVerifyImportVo> result = EasyPoiUtil.importExcelResult(file, 1, 1, AntiepidemicCommunityVerifyImportVo.class);
        List<AntiepidemicCommunityVerifyImportVo> importList = result.getList();
        if (CollUtil.isNotEmpty(importList)) {
            Map<String, AntiepidemicCommunityImportVo> importMap = new HashMap<>();
            String key;
            for (AntiepidemicCommunityVerifyImportVo entity : importList) {
                key = entity.getBuildingInfo();
                /*if (importMap.keySet().contains(key)) {
                    continue;
                }*/
                importMap.put(key, entity);
            }
            List<AntiepidemicBuilding> list = new ArrayList<>();
            for (Map.Entry<String, AntiepidemicCommunityImportVo> entry : importMap.entrySet()) {
                AntiepidemicCommunityImportVo userFrom = entry.getValue();
                // 查询是否存在
                AntiepidemicBuilding search = new AntiepidemicBuilding();
                search.setCommunityId(communityId);
                search.setBuildingInfo(userFrom.getBuildingInfo());
                List<AntiepidemicBuilding> booleanList = this.select(search);
                if (CollUtil.isNotEmpty(booleanList)) {
                    continue;
                }
                // 账号不存在，保存进用户表
                AntiepidemicBuilding antiepidemicBuilding = new AntiepidemicBuilding(sysUser);
                antiepidemicBuilding.setApplyId(applyId);
                antiepidemicBuilding.setCommunityId(communityId);
                antiepidemicBuilding.setOrderNum(userFrom.getOrderNum());
                antiepidemicBuilding.setBuildingInfo(userFrom.getBuildingInfo());
                list.add(antiepidemicBuilding);
            }
            // 保存
            if (CollUtil.isNotEmpty(list)) {
                antiepidemicBuildingDao.insertList(list);
            }
        }
        if (result.isVerfiyFail()) {
            // 如果错误，打印出提醒，直接返回
            int successNum = 0;
            int failNum = result.getFailList().size();
            if (result.getList() != null && result.getList().size() > 0) {
                successNum = result.getList().size();
            }
            String errorMsg = String.format("共导入%s条，成功%s条，失败%s条。", successNum + failNum, successNum, failNum);
            List<AntiepidemicCommunityVerifyImportVo> failList = result.getFailList();
            // 需要将成功条数也返回
            Map<String, Object> resutlMap = new HashMap<>();
            resutlMap.put("failList", failList);
            return new ReturnResult(ErrorCode.CODE_1, resutlMap, errorMsg);
        }
        return new ReturnResult();
    }
}